package jp.dip.ysato.excitewidget;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class DetailActivity extends Activity {
	class ShowCoupon extends AsyncTask<String, Integer, Coupon> {
		private ProgressDialog dialog;
		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(DetailActivity.this);
			dialog.setTitle(getString(R.string.getting_title));
			dialog.setMessage(getString(R.string.wait));
			dialog.setIndeterminate(false);
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.setCancelable(false);
			dialog.show();
		}
		@Override
		protected Coupon doInBackground(String... params) {
			Coupon coupon = new Coupon();
			CookieStore cookies;
			try {
				cookies = coupon.getLoginCookie(params[0], params[1]);
				coupon.getinfo(cookies);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return coupon;
		}
		@Override
		protected void onPostExecute(Coupon coupon) {
			int remain_ids[] = new int[] {R.id.FieldToral, R.id.Field1, R.id.Field2, R.id.Field3, R.id.Field4};
			int date_ids[] = new int[] {R.id.Remain1, R.id.Remain2, R.id.Remain3, R.id.Remain4};
			int sim_ids[] = new int[] {R.id.Sim1OnOff, R.id.Sim1TelNo, R.id.Sim2OnOff, R.id.Sim2TelNo, R.id.Sim3OnOff, R.id.Sim3TelNo};
			boolean show[] = new boolean[] {true, true, true};
			int start = 0;
			TelephonyManager telmgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
			String telno = telmgr.getLine1Number();
			for(int i = 0; i < remain_ids.length; i ++) {
				TextView v = (TextView) findViewById(remain_ids[i]);
				v.setText(coupon.getRemain(i));
			}
			for (int i = 0; i < date_ids.length; i++) {
				TextView v = (TextView) findViewById(date_ids[i]);
				v.setText(String.format("%1$tB", coupon.getMonth(i)));
			}
			Pattern p = Pattern.compile("(\\d+)-(\\d+)-(\\d+)");
			for(int i = 0; i < 3; i++) {
				String simtel = coupon.getSIM(i).getTel();
				Matcher m = p.matcher(simtel);
				m.find();
				simtel = m.group(1) + m.group(2) + m.group(3);
				if (simtel.equals(telno)) {
					show[i] = false;
					ToggleButton b = (ToggleButton) findViewById(R.id.Sim1OnOff);
					b.setChecked(coupon.getSIM(i).isFast());
					TextView v = (TextView) findViewById(R.id.Sim1TelNo);
					v.setText(coupon.getSIM(i).getTel());
					start = 2;
				}
			}
			for (int i = start; i < sim_ids.length; i += 2) {
				for(int j = 0; j < show.length; j++) {
					if (!show[j])
						continue;
					ToggleButton b = (ToggleButton) findViewById(sim_ids[i]);
					b.setChecked(coupon.getSIM(j).isFast());
					TextView v = (TextView) findViewById(sim_ids[i+1]);
					v.setText(coupon.getSIM(j).getTel());
					show[j] = false;
					break;
				}
			}
			dialog.dismiss();
		}
	}
	class UpdateSw extends AsyncTask<String, Void, Void> {
		private String tel;
		private boolean state; 
		private ProgressDialog dialog;
		public UpdateSw(String tel, boolean state) {
			this.tel = tel;
			this.state = state;
		}
		protected void onPreExecute() {
			dialog = new ProgressDialog(DetailActivity.this);
			dialog.setTitle(getString(R.string.apply));
			dialog.setMessage(getString(R.string.wait));
			dialog.setIndeterminate(false);
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.setCancelable(false);
			dialog.show();
		}
		@Override
		protected Void doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			Coupon coupon = new Coupon();
			try {
				CookieStore cookies = coupon.getLoginCookie(arg0[0], arg0[1]);
				coupon.setfast(cookies, tel, state);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void arg0) {
			dialog.dismiss();
		}		
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		int sim_ids[] = new int[] {R.id.Sim1OnOff, R.id.Sim2OnOff, R.id.Sim3OnOff};
		for (int i = 0; i < sim_ids.length; i++) {
			ToggleButton b = (ToggleButton) findViewById(sim_ids[i]);
			b.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					int sim_ids[] = new int[] {R.id.Sim1OnOff, R.id.Sim1TelNo, R.id.Sim2OnOff, R.id.Sim2TelNo, R.id.Sim3OnOff, R.id.Sim3TelNo};
					for (int i = 0; i < sim_ids.length; i += 2) {
						if (findViewById(sim_ids[i]) == arg0) {
							TextView t = (TextView) findViewById(sim_ids[i + 1]);
							String tel = t.getText().toString();
							DBHelper dbhelper = new DBHelper(DetailActivity.this);
							SQLiteDatabase db = dbhelper.getWritableDatabase();
							Cursor cur = db.query("account", new String[]{"rowid", "user", "password"}, null, null, null, null, null);
							if(cur.moveToFirst()) {
								String user = cur.getString(cur.getColumnIndex("user"));
								String pass = cur.getString(cur.getColumnIndex("password"));
								db.close();
								new UpdateSw(tel, ((ToggleButton)arg0).isChecked()).execute(user, pass);
							}
						}
							
					}
				}
			});
		}
		updateCoupon();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if(requestCode == 0) {
			if(resultCode == 1) {
				updateCoupon();
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.menu_login) {
			Intent intent = new Intent(this,LoginActivity.class);
			startActivityForResult(intent, 0);
			return true;
		} else {
			return super.onOptionsItemSelected(item);
		}
	}
	
	private void updateCoupon() {
		DBHelper dbhelper = new DBHelper(this);
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		Cursor cur = db.query("account", new String[]{"rowid", "user", "password"}, null, null, null, null, null);
		if(!cur.moveToFirst()) {
			db.close();
			Intent intent = new Intent(this,LoginActivity.class);
			startActivityForResult(intent, 0);
		} else {
			String user = cur.getString(cur.getColumnIndex("user"));
			String pass = cur.getString(cur.getColumnIndex("password"));
			db.close();
			new ShowCoupon().execute(new String[] {user, pass});
		}
		
	}
}
